/*
 * @Author: hrg
 * @Date: 2024-01-30 09:07:02
 * @LastEditTime: 2024-01-30 14:54:22
 * @FilePath: \study_go\study08_gin\gin_dome_10\mian.go
 * @Description:局部中间件
 */
package main

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

// 定义中间件：
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("中间件开始执行")
		// 设置变量到context中，可通过GET()获取
		c.Set("test", "中间件")
		// 执行函数
		c.Next()
		// 中间件执行完后续的事
		status := c.Writer.Status()
		fmt.Println("中间件执行完毕", status)
		t2 := time.Since(t)

		fmt.Println("time:", t2)

	}
}

func test(c *gin.Context) {

	req, _ := c.Get("test")

	fmt.Println("请求：", req)

	// 页面接收
	c.JSON(200, gin.H{
		"request": req,
	})
}

func main() {
	r := gin.New()

	r.GET("/test", MiddleWare(), test)

	r.GET("/test1", func(ctx *gin.Context) {
		ctx.JSON(200, gin.H{
			"success": "成功！",
		})
	})

	r.Run(":9090")

}
